package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.dto.SetmealDto;
import com.itheima.reggie.pojo.Dish;
import com.itheima.reggie.pojo.Setmeal;
import com.itheima.reggie.pojo.SetmealDish;
import com.itheima.reggie.service.DishService;
import com.itheima.reggie.service.SetmealDishService;
import com.itheima.reggie.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 套餐管理
 */
@RestController
@RequestMapping("setmeal")
@Slf4j
public class SetmealController {

    @Autowired
    private SetmealService setmealService;
    @Autowired
    private SetmealDishService setmealDishService;
    @Autowired
    private DishService dishService;

    /**
     * 按条件分页查询套餐
     *
     * @param curPage
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("page")
    public R<Page<SetmealDto>> querySetMealByPage(@RequestParam("page") Integer curPage,
                                                  Integer pageSize, String name) {
        Page<SetmealDto> page = setmealService.querySetMealByPage(curPage, pageSize, name);
        return R.success(page);
    }

    /**
     * 添加套餐
     *
     * @param setmealDto
     * @return
     */
    @PostMapping
    @CacheEvict(cacheNames = "setMealList", allEntries = true)
    public R<String> addSetMeal(@RequestBody SetmealDto setmealDto) {
        if (setmealDto.getSetmealDishes() == null) {
            return R.error("套餐中菜品数据错误");
        }
        setmealService.addSetMeal(setmealDto);
        return R.success("套餐添加成功");
    }

    /**
     * 根据套餐id查询套餐和套餐下的菜品
     *
     * @param id
     * @return
     */
    @GetMapping("{id}")
    public R<SetmealDto> querySetMealById(@PathVariable Long id) {
        SetmealDto setmealDto = setmealService.querySetMealById(id);
        return R.success(setmealDto);
    }


    /**
     * 修改套餐信息
     *
     * @param setmealDto
     * @return
     */
    @PutMapping
    @CacheEvict(cacheNames = "setMealList", allEntries = true)
    public R<String> updateSetMeal(@RequestBody SetmealDto setmealDto) {
        if (setmealDto.getSetmealDishes() == null) {
            return R.error("套餐中菜品数据错误");
        }
        setmealService.updateSetMeal(setmealDto);
        return R.success("修改套餐成功");
    }

    /**
     * 修改套餐状态
     *
     * @return
     */
    @PostMapping("status/{status}")
    @CacheEvict(cacheNames = "setMealList", allEntries = true)
    public R<String> batchUpdateSetMealStatus(@PathVariable Integer status, Long[] ids) {
        setmealService.lambdaUpdate()
                .set(Setmeal::getStatus, status)
                .set(Setmeal::getUpdateTime, LocalDateTime.now())
                .set(Setmeal::getUpdateUser, BaseContext.getCurrentId())
                .in(Setmeal::getId, Arrays.asList(ids))
                .update();
        return R.success("修改套餐状态成功");
    }

    /**
     * 删除套餐
     *
     * @param ids
     * @return
     */
    @DeleteMapping
    @CacheEvict(cacheNames = "setMealList", allEntries = true)
    public R<String> batchDeleteSetMeal(Long[] ids) {
        setmealService.batchDeleteSetMeal(Arrays.asList(ids));
        return R.success("套餐删除成功");
    }

    /**
     * 根据分类id查询所有起售套餐
     *
     * @param categoryId
     * @param status
     * @return
     */
    @GetMapping("list")
    @Cacheable(cacheNames = "setMealList", key = "#categoryId + ':' + #status",
            unless = "#result.data.size()<=0")
    public R<List<Setmeal>> querySetMealList(Long categoryId, Integer status) {
        List<Setmeal> setMeals = setmealService.lambdaQuery()
                .eq(status != null, Setmeal::getStatus, status)
                .eq(categoryId != null, Setmeal::getCategoryId, categoryId)
                .orderByDesc(Setmeal::getUpdateTime)
                .list();
        return R.success(setMeals);
    }

    /**
     * 查询套餐中的菜品和份数
     *
     * @param setMealId
     * @return
     */
    @GetMapping("dish/{setMealId}")
    public R<List<DishDto>> querySetMealDish(@PathVariable Long setMealId) {
//        List<SetmealDish> setMealDishes = setmealDishService.lambdaQuery()
//                .eq(SetmealDish::getSetmealId, setMealId)
//                .list();
//        List<Long> dishIds = setMealDishes.stream()
//                .map(SetmealDish::getDishId).collect(Collectors.toList());
//        List<Dish> dishes = dishService.listByIds(dishIds);
//        List<DishDto> dishDtoList = dishes.stream().map(dish -> {
//            DishDto dishDto = new DishDto();
//            BeanUtils.copyProperties(dish, dishDto);
//            SetmealDish setMealDish = setMealDishes.stream()
//                    .filter(setmealDish -> setmealDish.getDishId().equals(dish.getId()))
//                    .findFirst().get();
//            dishDto.setCopies(setMealDish.getCopies());
//            return dishDto;
//        }).collect(Collectors.toList());
        List<DishDto> dishDtoList = dishService.queryDishDtoBySetMealId(setMealId);
        return R.success(dishDtoList);
    }
}
